window.onload = function () {
    fullTable(tsList);
}

//将数组内容填充表格数据
function fullTable (array){
    let str = "";
    array.forEach(n=>{
        str+=`<tr><td><img src="${n.img}" style="width: 50px;height: 80px;: px"></td><td>${n.title}</td>
                <td>${n.author}</td><td>${n.money}</td><td>${n.id}</td><td>
                <input type="button" value="查看" onclick="see(${n.id})">
                <input type="button" value="加入购物车" onclick="seeShop(${n.id})">
</td></tr>`;
    });
    $("data").innerHTML=str;
}
//查看 加入购物车
function see(id) {
    //按编号获取查看对象
    var obj = tsList.find(n=>n.id==id);
    $("imgTxt").src=obj.img;
    $("titleTxt").innerHTML=obj.title;
    $("authorTxt").innerHTML=obj.author;
    $("moneyTxt").innerHTML=obj.money;
    $("info").style.visibility="visible"
}

// 加入购物车
var arr = [];
function seeShop(id) {
     var book = arr.find(n=>n.obj.id ==id);
    if (book!=null){
       book.num ++;
    }else {
        //按编号获取查看对象
        var obj = tsList.find(n=>n.id==id);
        var shops={obj,num:1,nums:obj.money}
       arr.push(shops)
        $("shop").style.visibility="visible"
        addToCart(arr);
    }
    priceNum()
}
//查询
function finByTitle() {
    //得到文本框的内容
    var nameStr = $("titleNameTxt").value;
    var newList = tsList.filter(n=>n.title.indexOf(nameStr)!=-1);
    fullTable(newList);
}

//购物车表信息录入
function addToCart(array) {
    let str = "";
    array.forEach(n=>{
        str+=`<tr><td>${n.obj.title}</td><td>${n.obj.money}</td><td>
             <input type="text" value="${n.num}" oninput="price(${n.obj.id},this.value)"></td>
             <td id="${n.obj.id}">${n.nums}</td><td>${n.obj.id}</td><td>
                <input type="button" value="移除商品" onclick="deleteShop(${n.obj.id})">
</td></tr>`;
});
    // console.log(${n.obj.id});
    $("data1").innerHTML=str;
}
//继续购物
function continueShop() {
    $("shop").style.visibility="hidden";
}
//移除商品
function deleteShop(id){
//找到指定编号的下标
    let index = arr.findIndex(n=>n.id == id);
    //删除指定下标的内容
    arr.splice(index,1);
    addToCart(arr)
    priceNum();
}
//获取单个商品总价
function price(id,num) {
    var a = arr.find(n=>n.obj.id==id)
    a.num=num;
    a.nums=num*a.obj.money;
    $(id).innerHTML=a.nums;
    priceNum();
}
//获取总共商品的价格
function priceNum() {
    let str=0;
    for (i=0;i<arr.length;i++){
        str+=arr[i].obj.money*arr[i].num;
    }
    $("moneyNumSpan").innerHTML=str;
}
//获得id
function $(id) {
    return document.getElementById(id);
}